<template>
  <div class="main">

    <el-tabs v-model="tabsActive" style="padding:20px; background:#FFF" type="card">
      <div class="main-title" v-if="tabsActive === 'second'">

      </div>
      <el-tab-pane label="活动信息" name="first">
        <section v-loading="pageLoading">
          <el-form class="section-content" :model="formData" size="medium" ref="form" label-width="150px">
            <div class="section-header">
              <span>活动信息</span>
            </div>
            <div class="section-content">
              <el-form-item label="活动名称：">
                {{formData.boxSeries.seriesName}}
              </el-form-item>
              <el-form-item label="是否上架：">
                <span v-if="formData.boxSeries.upshelf" style="color: green">已上架</span>
                <span v-else style="color: #9b9b9b">已下架</span>
              </el-form-item>
              <el-form-item label="是否展示：">
                <span v-if="formData.boxSeries.isShow" style="color: green">是</span>
                <span v-else style="color: #9b9b9b">否</span>
              </el-form-item>
            </div>
            <div class="section-header">
              <span>活动商品</span>
            </div>
            <div class="section-content">
              <div class="add-btn-block">
                <el-button type="primary" size="small" icon="el-icon-circle-plus" plain @click="addGoods" :disabled="(formData.boxGoods.length>=1&&formData.boxSeries.seriesType===3) || formData.boxSeries.upshelf===-1">添加商品</el-button>
                <el-button type="primary" size="small" icon="el-icon-circle-plus" plain @click="addPackage" :disabled="(formData.boxGoods.length>=1&&formData.boxSeries.seriesType===3) || formData.boxSeries.upshelf===-1" v-if="formData.boxSeries.seriesType!==3">添加套餐</el-button>
              </div>
              <el-collapse v-model="activeName" accordion>
                <el-collapse-item v-for="(goodsItem, goodsIndex) in formData.boxGoods" :key="goodsIndex" :name="goodsIndex">
                  <template slot="title">
                    <span v-if="goodsItem.boxId" style="margin: 0 22px"></span>
                    <i v-else class="el-icon-delete" title="删除商品" @click.stop="delGoods(goodsItem.boxId, goodsIndex)"></i>
                    {{goodsItem.type===1?'商品':'套餐'}}{{goodsIndex+1}}：{{goodsItem.name}}<span v-if="goodsItem.type===1">【{{goodsItem.goodsAttr && goodsItem.goodsAttr.attrValue1}}】【{{goodsItem.goodsAttr && goodsItem.goodsAttr.attrValue2}}】</span>
                    <span style="color: #a94442" v-if="goodsItem.goodsAttr && goodsItem.goodsAttr.totalSkuNumber"> |
                      可分配库存：{{goodsItem.goodsAttr && goodsItem.goodsAttr.totalSkuNumber}}</span>
                  </template>
                  <div class="goods-item">
                    <el-form-item label="购买等级：" :prop="`boxGoods[${goodsIndex}].tempRoles`">
                      VIP会员
                    </el-form-item>
                    <el-form-item :label="`${goodsItem.type===1?'商品名称：':'套餐名称：'}`" :prop="`boxGoods[${goodsIndex}].name`" :rules="commonRules.notNullRule">
                      <el-input v-model="goodsItem.name" :disabled="formData.boxSeries.upshelf===-1">
                      </el-input>
                    </el-form-item>
                    <el-form-item :label="`${goodsItem.type===1?'商品副标题：':'套餐副标题：'}`">
                      <el-input v-model="goodsItem.subTitle" :disabled="formData.boxSeries.upshelf===-1">
                      </el-input>
                    </el-form-item>
                    <el-form-item label="商品标签：">
                      <el-input maxlength="8" v-model="goodsItem.goodsLabel" placeholder="输入标签八个字以内" :disabled="formData.boxSeries.upshelf===-1">
                      </el-input>
                    </el-form-item>
                    <el-form-item :label="`${goodsItem.type===1?'商品单位：':'套餐单位：'}`" :prop="`boxGoods[${goodsIndex}].boxCount`" :rules="commonRules.numberRule">
                      <!-- 一单位 = -->
                      一箱 =
                      <el-input type="number" v-model="goodsItem.boxCount" style="width: 150px"
                        :disabled="!!(goodsItem.boxId&&formData.boxSeries.upshelf) || formData.boxSeries.upshelf===-1">
                        <template slot="append">件</template>
                      </el-input>
                    </el-form-item>
                    <el-form-item label="会员价：" :prop="`boxGoods[${goodsIndex}].marketPrice`" :rules="commonRules.priceRuleZeroT">
                      <el-input type="number" v-model="goodsItem.marketPrice" style="width: 194px"
                        :disabled="!!(goodsItem.boxId&&formData.boxSeries.upshelf) || formData.boxSeries.upshelf===-1">
                        <template slot="append">积分/箱</template>
                      </el-input>
                    </el-form-item>
                    <el-form-item label="商品售价：" :prop="`boxGoods[${goodsIndex}].ordinaryPrice`" :rules="commonRules.priceRule">
                      <el-input type="number" v-model="goodsItem.ordinaryPrice" style="width: 194px"
                        :disabled="!!(goodsItem.boxId&&formData.boxSeries.upshelf) || formData.boxSeries.upshelf===-1">
                        <template slot="append">积分/箱</template>
                      </el-input>
                    </el-form-item>
                    <el-form-item :label="`${goodsItem.type===1?'商品主图：':'套餐主图：'}`" :prop="`boxGoods[${goodsIndex}].image`" :rules="commonRules.notNullRule">
                      <el-upload class="avatar-uploader" accept="image/*" :action="upladUrl" name="file" :show-file-list="false"
                        :before-upload="beforeUpload" :on-success="(res)=>{
                                        goodsItem.image = replaceImgUrl(res.filePath);
                                    }" :disabled="formData.boxSeries.upshelf===-1">
                        <img v-if="goodsItem.image" :src="goodsItem.image" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                    </el-form-item>
                    <el-form-item :label="`${goodsItem.type===1?'商品图片：':'套餐图片：'}`" :prop="`boxGoods[${goodsIndex}].tempImageList`" :rules="commonRules.notNullRule">
                      <ul class="upload-img-list">
                        <draggable v-model="goodsItem.tempImageList" :options="{group:'goodsGalleryList'}" @start="drag=true" @end="drag=false">
                          <li class="img-preview" v-for="(imgItem, imgIndex) of goodsItem.tempImageList" :key="imgIndex">
                            <img :src="imgItem" alt="">
                            <div class="img-preview-mask" v-show="formData.boxSeries.upshelf!==-1">
                              <div class="mask-btn">
                                <i title="删除" class="el-icon-delete" @click="()=>{goodsItem.tempImageList.splice(imgIndex, 1)}"></i>
                              </div>
                            </div>
                          </li>
                        </draggable>
                        <li>
                          <label class="upload-btn">
                            <input type="file" @change="(event)=>{uploadImg(event, goodsItem.tempImageList)}" :disabled="formData.boxSeries.upshelf===-1" />
                            <i class="el-icon-plus"></i>
                          </label>
                        </li>
                      </ul>
                      <div v-if="goodsItem.tempImageList.length>1" style="color: red">拖拽已上传的图片可以进行排序</div>
                    </el-form-item>
                    <el-form-item :label="`${goodsItem.type===1?'商品简介：':'套餐简介：'}`">
                      <el-input type="textarea" v-model="goodsItem.intro" maxLength="300" :disabled="formData.boxSeries.upshelf===-1"></el-input>
                    </el-form-item>
                    <el-form-item :label="`${goodsItem.type===1?'商品故事：':'套餐故事：'}`">
                      <el-input type="textarea" v-model="goodsItem.story" :disabled="formData.boxSeries.upshelf===-1"></el-input>
                    </el-form-item>
                    <el-form-item :label="`${goodsItem.type===1?'商品详情：':'套餐详情：'}`" :prop="`boxGoods[${goodsIndex}].comment`" :rules="commonRules.notNullRule">
                      <tinymce :height="520" v-model="goodsItem.comment" :disabled="formData.boxSeries.upshelf===-1"></tinymce>
                    </el-form-item>
                    <el-form-item label="赠品商品：" :prop="`boxGoods[${goodsIndex}].boxPresentGoods`">
                      <el-button type="primary" size="small" icon="el-icon-circle-plus" plain @click="addPresent('0', goodsItem)">添加商品</el-button>
                    </el-form-item>
                    <el-form-item label="" v-if="goodsItem.boxPresentGoods && goodsItem.boxPresentGoods.length">
                      <template v-for="(presentGoods, presentIndex) in goodsItem.boxPresentGoods">
                        <template v-if="presentGoods.deleteFlag === 1">
                          <div class="present-item" :key="presentIndex">
                            <i class="el-icon-error" v-if="((!presentGoods.boxPresentId&&formData.boxSeries.upshelf) || !formData.boxSeries.upshelf) &&presentGoods.rule===1"
                              @click.stop="delPresentGoods(goodsItem.boxPresentGoods, presentIndex)" title="删除赠品"></i>
                            <template v-if="presentGoods.type===0">
                              <el-form-item label="商品名称：" label-width="100px">
                                {{presentGoods.name}}【{{presentGoods.goodsAttr && presentGoods.goodsAttr.attrValue1}}】【{{presentGoods.goodsAttr && presentGoods.goodsAttr.attrValue2}}】
                              </el-form-item>
                              <el-form-item label="商品图片：" label-width="100px" :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].img`"
                                :rules="commonRules.notNullRule">
                                <el-upload class="avatar-uploader" accept="image/*" :action="upladUrl" name="file" :show-file-list="false" :disabled="formData.boxSeries.upshelf===-1"
                                  :before-upload="beforeUpload" :on-success="(res)=>{presentGoods.img = replaceImgUrl(res.filePath);}">
                                  <img v-if="presentGoods.img" :src="presentGoods.img" class="avatar">
                                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                              </el-form-item>
                              <el-form-item label="赠送规则：" label-width="100px" :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].rule`"
                                :rules="commonRules.notNullRule">
                                <el-select v-model="presentGoods.rule" placeholder="请选择"
                                  :disabled="true" @change="(val) => {
                                  if (val===2) {presentGoods.buyNum2 = 0;presentGoods.giveNum2 = 0};
                                }">
                                  <el-option label="单次满赠" :value="1"></el-option>
                                </el-select>
                                <el-button type="text" @click="addRules(goodsIndex, presentIndex)" v-show="((!presentGoods.boxPresentId&&formData.boxSeries.upshelf) || !formData.boxSeries.upshelf) &&presentGoods.rule===1">添加规则</el-button>
                              </el-form-item>
                              <el-form-item label="规则1" label-width="100px" label-position="left">
                                <el-row>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].buyNum`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.buyNum"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">箱</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                  <el-col :lg="2" :xl="1" align="center">送</el-col>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].giveNum`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.giveNum"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">箱</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                  <el-col :offset="1" :lg="2" :xl="1" align="center">1箱=</el-col>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].boxCount`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.boxCount"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">件</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                </el-row>
                              </el-form-item>
                              <el-form-item label="规则2" label-width="100px" label-position="lefift" v-if="(presentGoods.isSecondRule||presentGoods.buyNum2) && presentGoods.rule===1">
                                <el-row>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].buyNum2`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.buyNum2"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <!-- <template slot="append">单位</template> -->
                                        <template slot="append">箱</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                  <el-col :lg="2" :xl="1" align="center">送</el-col>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].giveNum2`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.giveNum2"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <!-- <template slot="append">单位</template> -->
                                        <template slot="append">箱</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                  <!-- <el-col :offset="1" :lg="2" :xl="1" align="center">1单位=</el-col> -->
                                  <el-col :offset="1" :lg="2" :xl="1" align="center">1箱=</el-col>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].boxCount`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.boxCount"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">件</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                  <el-col :lg="2" :xl="1" align="center">
                                    <el-button type="text" @click="delRules(goodsIndex, presentIndex)" v-show="((!presentGoods.boxPresentId&&formData.boxSeries.upshelf) || !formData.boxSeries.upshelf) &&presentGoods.rule===1">移除</el-button>
                                  </el-col>
                                </el-row>
                              </el-form-item>
                              <!--<el-form-item label="数量：" label-width="100px" :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].presentNum`" :rules="commonRules.skuNumberRule">
                                                      <el-input type="number" v-model="presentGoods.presentNum" :disabled="!(formData.boxSeries.upshelf&&formData.boxSeries.isSell&&goodsItem.upshelf&&goodsItem.isSell)">
                                                          <template slot="append">单位</template>
                                                      </el-input> 填 0 代表无限制
                                                  </el-form-item>-->
                            </template>
                            <template v-if="presentGoods.type===1">
                              <el-form-item label="赠品名称：" label-width="100px" label-position="left">
                                {{presentGoods.name}}
                              </el-form-item>
                              <el-form-item label="赠送等级：" label-width="100px" :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].roles`"
                                :rules="commonRules.notNullRule">
                                <el-select v-model="presentGoods.roles" placeholder="请选择"
                                  :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                  <el-option label="全部" value="2,3"></el-option>
                                  <!-- <el-option label="普通会员" value="0,1"></el-option> -->
                                  <el-option label="大区" value="2"></el-option>
                                  <el-option label="董事" value="3"></el-option>
                                </el-select>
                              </el-form-item>
                              <el-form-item label="赠送规则：" label-width="100px" :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].rule`"
                                :rules="commonRules.notNullRule">
                                <el-select v-model="presentGoods.rule" placeholder="请选择"
                                  :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)" @change="(val) => {
                                  if (val===2) {presentGoods.buyNum2 = 0;presentGoods.giveNum2 = 0}
                                }">
                                  <el-option label="单次满赠" :value="1"></el-option>
                                  <el-option label="累计赠送" :value="2"></el-option>
                                </el-select>
                                <el-button type="text" @click="addRules(goodsIndex, presentIndex)" v-show="((!presentGoods.boxPresentId&&formData.boxSeries.upshelf) || !formData.boxSeries.upshelf) &&presentGoods.rule===1">添加规则</el-button>
                              </el-form-item>
                              <el-form-item label="规则1" label-width="100px" label-position="left">
                                <el-row>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].buyNum`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.buyNum"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">箱</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                  <el-col :lg="2" :xl="1" align="center">送</el-col>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].giveNum`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.giveNum" :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">个</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                </el-row>
                              </el-form-item>
                              <el-form-item label="规则2" label-width="100px" label-position="left" v-if="(presentGoods.isSecondRule||presentGoods.buyNum2) && presentGoods.rule===1">
                                <el-row>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].buyNum2`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.buyNum2"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">箱</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                  <el-col :lg="2" :xl="1" align="center">送</el-col>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].giveNum2`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.giveNum2" :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">个</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                  <el-col :lg="2" :xl="1" align="center">
                                    <el-button type="text" @click="delRules(goodsIndex, presentIndex)" v-show="((!presentGoods.boxPresentId&&formData.boxSeries.upshelf) || !formData.boxSeries.upshelf) &&presentGoods.rule===1">移除</el-button>
                                  </el-col>
                                </el-row>
                              </el-form-item>
                            </template>
                            <template v-if="presentGoods.type===2">
                              <el-form-item label="物品名称：" label-width="100px" :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].name`"
                                :rules="commonRules.notNullRule">
                                <el-input v-model="presentGoods.name" style="width: 100%; max-width: 500px">
                                </el-input>
                              </el-form-item>
                              <el-form-item label="物品图片：" label-width="100px" :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].img`"
                                :rules="commonRules.notNullRule">
                                <el-upload class="avatar-uploader" :action="upladUrl" name="file" :show-file-list="false" :before-upload="beforeUpload"
                                  :on-success="(res)=>{
                                                            presentGoods.img = replaceImgUrl(res.filePath);
                                                          }">
                                  <img v-if="presentGoods.img" :src="presentGoods.img" class="avatar">
                                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                              </el-form-item>
                              <el-form-item label="赠送等级：" label-width="100px" :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].roles`"
                                :rules="commonRules.notNullRule">
                                <el-select v-model="presentGoods.roles" placeholder="请选择"
                                  :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                  <el-option label="全部" value="0,1,2,3"></el-option>
                                  <el-option label="普通会员" value="0,1"></el-option>
                                  <el-option label="大区" value="2"></el-option>
                                  <el-option label="董事" value="3"></el-option>
                                </el-select>
                              </el-form-item>
                              <el-form-item label="赠送规则：" label-width="100px" :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].rule`"
                                :rules="commonRules.notNullRule">
                                <el-select v-model="presentGoods.rule" placeholder="请选择"
                                  :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)" @change="(val) => {
                                  if (val===2) {presentGoods.buyNum2 = 0;presentGoods.giveNum2 = 0}
                                }">
                                  <el-option label="单次满赠" :value="1"></el-option>
                                  <el-option label="累计赠送" :value="2"></el-option>
                                </el-select>
                                <el-button type="text" @click="addRules(goodsIndex, presentIndex)" v-show="((!presentGoods.boxPresentId&&formData.boxSeries.upshelf) || !formData.boxSeries.upshelf) &&presentGoods.rule===1">添加规则</el-button>
                              </el-form-item>
                              <el-form-item label="规则1" label-width="100px" label-position="left">
                                <el-row>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].buyNum`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.buyNum"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">箱</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                  <el-col :lg="2" :xl="1" align="center">送</el-col>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].giveNum`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.giveNum"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">个</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                </el-row>
                              </el-form-item>
                              <el-form-item label="规则2" label-width="100px" label-position="left" v-if="(presentGoods.isSecondRule||presentGoods.buyNum2) && presentGoods.rule===1">
                                <el-row>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].buyNum2`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.buyNum2"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">箱</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                  <el-col :lg="2" :xl="1" align="center">送</el-col>
                                  <el-col :lg="6" :xl="3">
                                    <el-form-item :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].giveNum2`"
                                      :rules="commonRules.numberRule">
                                      <el-input type="number" v-model="presentGoods.giveNum2"
                                        :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                        <template slot="append">个</template>
                                      </el-input>
                                    </el-form-item>
                                  </el-col>
                                  <el-col :lg="2" :xl="1" align="center">
                                    <el-button type="text" @click="delRules(goodsIndex, presentIndex)" v-show="((!presentGoods.boxPresentId&&formData.boxSeries.upshelf) || !formData.boxSeries.upshelf) &&presentGoods.rule===1">移除</el-button>
                                  </el-col>
                                </el-row>
                              </el-form-item>
                              <el-form-item label="数量：" label-width="100px"
                                :prop="`boxGoods[${goodsIndex}].boxPresentGoods[${presentIndex}].presentNum`" :rules="commonRules.skuNumberRule">
                                <el-input type="number" v-model="presentGoods.presentNum"
                                  :disabled="!!(presentGoods.boxPresentId&&formData.boxSeries.upshelf)">
                                  <template slot="append">个</template>
                                </el-input> 填 0 代表无限制
                              </el-form-item>
                            </template>
                          </div>
                        </template>
                      </template>
                    </el-form-item>
                    <el-form-item label="是否上架">
                      <el-switch v-model="goodsItem.upshelf" active-color="#13ce66" inactive-color="#ff4949" active-text="是" inactive-text="否" :disabled="formData.boxSeries.upshelf===-1"
                        :active-value="1" :inactive-value="0" @change="handleUpshelf(goodsIndex, goodsItem.upshelf)">
                      </el-switch>
                    </el-form-item>
                    <el-form-item label="是否展示">
                      <el-switch v-model="goodsItem.isSell" active-color="#13ce66" inactive-color="#ff4949" active-text="是" inactive-text="否"
                        :active-value="1" :inactive-value="0" :disabled="!goodsItem.upshelf || formData.boxSeries.upshelf===-1">
                      </el-switch>
                    </el-form-item>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
            <!--运费2.0版本废弃-->
            <div class="section-header">
              <span>活动运费</span>
            </div>
            <div class="section-content">
              <el-form-item label="运费模板:" prop="boxSeries.freightTemplateId" :rules="rules.freightTemplateId">
                <el-select v-model="formData.boxSeries.freightTemplateId" placeholder="请选择" filterable clearable
                  :disabled="formData.boxSeries.upshelf===1 || formData.boxSeries.upshelf===-1?true:false">
                  <el-option :key="item.id" :label="item.name" :value="item.id" v-for="item in freightList"></el-option>
                </el-select>
              </el-form-item>
              <!--<el-row align="center">-->
              <!--<el-col :md="6" >-->
              <!--<el-form-item label="首件：" prop="boxSeries.firstPiece" :rules="rules.nonnegativeInteger"  >-->
              <!--<el-input type="number" v-model="formData.boxSeries.firstPiece" :disabled="formData.boxSeries.upshelf==1?true:false">-->
              <!--<template slot="append">元/单位</template>-->
              <!--</el-input>   -->
              <!--</el-form-item> -->
              <!--</el-col>-->
              <!--<el-col :md="6" >-->
              <!--<el-form-item label="续件："  prop="boxSeries.continuePiece" :rules="rules.nonnegativeInteger" >-->
              <!--<el-input type="number" v-model="formData.boxSeries.continuePiece"  :disabled="formData.boxSeries.upshelf==1?true:false">-->
              <!--<template slot="append">元/单位</template>-->
              <!--</el-input>   -->
              <!--</el-form-item> -->
              <!--</el-col>-->
              <!--</el-row>   -->
            </div>
            <div class="footer-block">
              <el-button type="success" size="small" :loading="saveLoading" @click="save">保存</el-button>
              <el-button type="primary" size="small" @click="$router.push({name: 'boxTransActivity'})" plain>返回</el-button>
            </div>
          </el-form>
          <el-dialog title="选择规格" :visible.sync="showSelectPop">
            <el-form :model="tempGoodsDetail" size="medium" ref="tempGoodsDetailForm" label-width="0px">
              <el-table v-if="tempGoodsDetail.goodsAttr" :data="tempGoodsDetail.goodsAttr" highlight-current-row border>
                <el-table-column align="center" width="50">
                  <template slot-scope="scope">
                    <label class="input-radio">
                      <input type="radio" :value="scope.$index" v-model="tempGoodsAttrIndex" />
                      <span></span>
                    </label>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="商品">
                  <template>
                    {{tempGoodsDetail.goods.name}}
                  </template>
                </el-table-column>
                <el-table-column
                  v-for="(item, index) in [{id: 'attrId1',prop: 'attrValue1'},{id:'attrId2',prop: 'attrValue2'},{id:'attrId3',prop: 'attrValue3'},{id:'attrId4',prop: 'attrValue4'},{id:'attrId5',prop: 'attrValue5'},{id:'attrId6',prop: 'attrValue6'}]"
                  v-show="tempGoodsDetail.goodsAttr[0][item.prop]" :key="index" align="center" :label="'属性值'+(index+1)" :prop="item.prop"
                  min-width="100px">
                </el-table-column>
                <el-table-column align="center" label="库存数" min-width="90px">
                  <template slot-scope="$scope">
                    可分配：{{$scope.row.totalSkuNumber}}<br />
                    <!--已分配：{{($scope.row.distributedSkuNumber||0)+($scope.row.soldNumber||0)}}<br/>
                                <el-form-item v-if="$scope.row.totalSkuNumber+($scope.row.distributedSkuNumber||0)" :prop="'goodsAttr['+$scope.$index+'].skuNumber'" :rules="commonRules.skuNumberRule" style="margin-bottom: 30px">
                                    <el-input-number v-model="$scope.row.skuNumber" :min="1" :max="$scope.row.totalSkuNumber+($scope.row.distributedSkuNumber||0)" :precision="0" :controls="false" style="width: 100%"></el-input-number>
                                </el-form-item>-->
                    <span v-if="!($scope.row.totalSkuNumber+($scope.row.distributedSkuNumber||0))" style="color: red">库存不足</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="selectGoodsSku" :loading="btnLoading">确定</el-button>
              <el-button @click="showSelectPop = false">取消</el-button>
            </div>
          </el-dialog>
        </section>
      </el-tab-pane>
      <el-tab-pane label="评论列表" name="second">
        <CommontTable v-if="commontGoods.length > 0" :goods="commontGoods" :goodsType="4" :upshelf="formData.boxSeries.upshelf"/>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>
<script>
import draggable from 'vuedraggable'
import Sortable from 'sortablejs'
import Tinymce from '@/components/Tinymce'
import { getAllList } from '@/api/freight'
import CommontTable from '@/components/CommontTable'
export default {
  name: 'newBoxGoodsLists',
  props: {
    id: { default: '' }
  },
  components: {
    Tinymce,
    draggable,
    Sortable,
    CommontTable
  },
  data() {
    const validNum = (rule, value, callback) => {
      if (!value) {
        return callback()
      }
      if (!/^\d+$/.test(value)) {
        return callback(new Error('非正整数'))
      }
      return callback()
    }
    return {
      activityChannel: {
        '0': '零售',
        '1': '礼包',
        '2': '零售+礼包',
        '3': '云仓'
      },
      tags: {
        "0" : "无",
        "1" : "ZHO专属"
      },
      commontGoods: [],
      isEdit: true,
      pageLoading: true,
      tabsActive: 'first',
      listQuery: {
        seriesId: this.id
      },
      formData: {
        boxRules: [],
        boxGoods: [],
        boxSeries: {
          perUnit: '',
          limitDate: '',
          freightTemplateId: '' //运费模板
        }
      },
      formRules: {},
      activeName: '',
      showSelectPop: false,
      btnLoading: false,
      tempGoodsType: 1,
      tempGoodsItem: {},
      tempGoodsDetail: {},
      tempGoodsAttrIndex: 0,
      saveLoading: false,
      rules: {
        nonnegativeInteger: [
          { required: true, message: '不能为空', trigger: 'change' },
          { validator: validNum, trigger: 'change' }
        ],
        freightTemplateId: [
          { required: true, message: '不能为空', trigger: 'change' }
        ]
      },
      freightList: []
    }
  },
  created() {
    this.getList()
    this.getAllTpl()
  },
  methods: {
    // 处理商品是否上架
    handleUpshelf (goodsIndex, upshelf) {
      if (this.$route.query.upshelf) {
        let i = 0
        this.formData.boxGoods.forEach((item) => {
          if (item.upshelf) {
            i++
          }
        })
        if (i === 0) {
          this.$set(this.formData.boxGoods[goodsIndex], 'upshelf', 1);
          this.$message.error('请先下架箱起活动')
          return false
        }
      }
      if(!upshelf){
        this.$set(this.formData.boxGoods[goodsIndex], 'isSell', 0);
      }
    },
    // // 添加赠品规则
    addRules (goodsIndex, presentIndex) {
      this.$set(this.formData.boxGoods[goodsIndex].boxPresentGoods[presentIndex], 'isSecondRule', true);
    },
    // 删除赠品规则
    delRules (goodsIndex, presentIndex) {
      this.$set(this.formData.boxGoods[goodsIndex].boxPresentGoods[presentIndex], 'isSecondRule', false);
      this.$set(this.formData.boxGoods[goodsIndex].boxPresentGoods[presentIndex], 'buyNum2', 0);
      this.$set(this.formData.boxGoods[goodsIndex].boxPresentGoods[presentIndex], 'giveNum2', 0);
    },
    addCommon() {
      this.commonForm()
    },
    // 获取模板列表
    getAllTpl() {
      getAllList()
        .then(res => {
          if (res.code == 0) {
            this.freightList = res.data
          } else {
            this.$message({
              type: 'error',
              message: res.msg,
              duration: 2000
            })
          }
        })
        .catch(err => {
          this.$message({
            type: 'error',
            message: '未知错误',
            duration: 2000
          })
        })
    },
    getList() {
      this.pageLoading = true
      this.request({
        url: '/bsnl-product/box/goods/list',
        method: 'get',
        params: this.listQuery
      })
        .then(({ data }) => {
          if (data) {
            if (data.boxRules && !data.boxRules.length) {
              this.isEdit = false
              data.boxRules.push({
                seriesId: this.id,
                minBox: '',
                maxBox: '',
                commission: ''
              })
            }
            data.boxGoods.map(item => {
              var aaarrr = item.roles.split(',')
              item.tempRoles = []
              for (var i = 0; i < aaarrr.length; i++) {
                if (aaarrr[i] == 0) {
                  item.tempRoles.push('0,1')
                } else if (aaarrr[i] == 2) {
                  item.tempRoles.push('2')
                } else if (aaarrr[i] == 3) {
                  item.tempRoles.push('3')
                } else if (aaarrr[i] == 4) {
                  item.tempRoles.push('4')
                } else if (aaarrr[i] == 5) {
                  item.tempRoles.push('5')
                } else if (aaarrr[i] == 6) {
                  item.tempRoles.push('6')
                } else if (aaarrr[i] == 7) {
                  item.tempRoles.push('7')
                } else if (aaarrr[i] == 8) {
                  item.tempRoles.push('8')
                } else if (aaarrr[i] == 9) {
                  item.tempRoles.push('9')
                }
              }
              item.tempImageList = item.imageList.split(',')
            })
            data.boxSeries.freightTemplateId = data.boxSeries.freightTemplateId
              ? data.boxSeries.freightTemplateId + ''
              : ''
            this.goodsId = data.boxSeries.seriesId
            this.formData = data
            data.boxGoods.forEach(it => {
              this.commontGoods.push({
                value: it.boxId,
                label: it.name
              })
            })
          }
          this.pageLoading = false
        })
        .catch(err => {
          console.log(err)
          this.pageLoading = false
        })
    },
    addRule() {
      this.formData.boxRules.push({
        seriesId: this.id,
        minBox: '',
        maxBox: '',
        commission: ''
      })
    },
    delRule(index) {
      this.formData.boxRules.splice(index, 1)
    },
    uploadImg(event, item) {
      const file = event.target.files[0]
      this.picFileUpload(file, res => {
        item.push(this.replaceImgUrl(res.filePath))
      })
    },
    addPresent(command, goodsItem) {
      switch (command) {
        case '0':
          this.tempGoodsType = 0
          this.tempGoodsItem = goodsItem
          this.checkGoods([], 1, true)
            .then(val => {
              this.request({
                url: '/bsnl-product/goods/details',
                method: 'get',
                params: {
                  id: val[0].id
                }
              }).then(({ data }) => {
                data.goodsAttr.map(item => {
                  item.skuNumber = 1
                  item.number = 1
                })
                this.tempGoodsDetail = data
                this.showSelectPop = true
              })
            })
            .catch(err => {
              this.tempGoodsDetail = {}
            })
          break
        case '1':
          goodsItem.boxPresentGoods = [
            {
              name: '大区名额',
              boxId: goodsItem.boxId ? goodsItem.boxId : null,
              type: 1,
              roles: '0,1',
              rule: 1,
              buyNum: 2,
              giveNum: 1,
              buyNum2: 0,
              giveNum2: 0,
              deleteFlag: 1,
              isSecondRule: false
            }
          ].concat(goodsItem.boxPresentGoods)
          break
        case '2':
          goodsItem.boxPresentGoods = [
            {
              boxId: goodsItem.boxId ? goodsItem.boxId : null,
              type: 2,
              name: '',
              img: '',
              roles: '0,1',
              rule: 1,
              buyNum: 2,
              giveNum: 1,
              buyNum2: 0,
              giveNum2: 0,
              presentNum: 1,
              deleteFlag: 1,
              isSecondRule: false
            }
          ].concat(goodsItem.boxPresentGoods)
          break
        default:
          break
      }
    },
    delPresentGoods(boxPresentGoods, presentItem) {
      this.$confirm(`确定要删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 如果是下架编辑
          if (this.formData.boxSeries.upshelf === 0) {
            this.$set(boxPresentGoods[presentItem], 'deleteFlag', 0)
          } else {
            boxPresentGoods.splice(presentItem, 1)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    delGoods(boxId, goodsIndex) {
      this.$confirm(
        boxId ? `该删除将直接从数据库删除，确定要删除吗?` : `确定要删除吗?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          if (boxId) {
            this.request({
              url: '/bsnl-product/box/goods/doDelete',
              method: 'get',
              params: { boxId }
            })
              .then(() => {
                this.formData.boxGoods.splice(goodsIndex, 1)
                this.$message.success('删除成功')
              })
              .catch(err => {
                console.log(err)
              })
          } else {
            this.formData.boxGoods.splice(goodsIndex, 1)
            this.$message.success('删除成功')
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    addGoods() {
      this.tempGoodsType = 1
      this.checkGoods([], 1, true)
        .then(val => {
          this.request({
            url: '/bsnl-product/goods/details',
            method: 'get',
            params: {
              id: val[0].id
            }
          }).then(({ data }) => {
            data.goodsAttr.map(item => {
              item.skuNumber = 1
              item.number = 1
            })
            this.tempGoodsDetail = data
            this.showSelectPop = true
          })
        })
        .catch(err => {
          this.tempGoodsDetail = {}
        })
    },
    // 选套餐
    addPackage(){
      let selected = this.formData.boxGoods.filter(item=>item.type===2).map(item => {
        return {
          packageId: item.packageId,
          id: item.id,
          name: item.name,
          Sell: item.isSell,
          price: item.price,
          type: 1
        }
      });

      this.packageChoose({type: 'combo', existsPresetFlag: 0}, selected).then(val => {
        val.map(item => {
          if (this.tempGoodsType === 1) {
            let flag = true
            this.formData.boxGoods.map((i, index) => {
              if (i.packageId === item.packageId) {
                flag = false
              }
            })
            if (flag) {
              this.formData.boxGoods.push({
                seriesId: this.id,
                goodsId: '',
                goodsSkuId: '',
                packageId: item.packageId,
                type: 2,
                roles: '0,1',
                tempRoles: [0, 1],
                name: item.name,
                subTitle: item.subTitle,
                goodsLabel:'',
                boxCount: 1,
                minnum: '',
                boxNum: '',
                regionPrice: '',
                directorPrice: '',
                areaCommission: '',
                recommAreaCommission: '',
                recommDirectorCommission: '',
                directorCommission: '',
                image: item.image,
                imageList: '',
                tempImageList: item.imgUrls ? item.imgUrls.split(',') : [],
                intro: item.remarks,
                story: item.story,
                comment: item.intro,
                boxPresentGoods: [],
                upshelf: 1,
                isSell: 1
              })
            }
          } else {
            this.tempGoodsItem.boxPresentGoods = [
              {
                type: 0,
                boxId: this.tempGoodsItem.boxId ? this.tempGoodsItem.boxId : null,
                goodsId: this.tempGoodsDetail.goods.goodsId,
                goodsSkuId: this.tempGoodsDetail.goodsAttr[this.tempGoodsAttrIndex]
                  .skuCode,
                name: this.tempGoodsDetail.goods.name,
                img: this.tempGoodsDetail.goods.image,
                roles: '0,1',
                rule: 1,
                buyNum: 1,
                giveNum: 1,
                buyNum2: 0,
                giveNum2: 0,
                boxCount: 1,
                presentNum: 1,
                deleteFlag: 1,
                isSecondRule: false,
                goodsAttr: {
                  ...this.tempGoodsDetail.goodsAttr[this.tempGoodsAttrIndex],
                  associationId: this.id
                }
              }
            ].concat(this.tempGoodsItem.boxPresentGoods)
          }
        })
      })
    },
    selectGoodsSku() {
      if (
        this.tempGoodsDetail.goodsAttr[this.tempGoodsAttrIndex].totalSkuNumber <
        1
      ) {
        this.$message.warning('库存不足，请选择其他商品')
        return false
      }
      if (this.tempGoodsType === 1) {
        if (
          this.formData.boxGoods.some(
            item =>
              item.goodsSkuId ===
              this.tempGoodsDetail.goodsAttr[this.tempGoodsAttrIndex].skuCode
          )
        ) {
          this.$message.warning('商品已存在，请选择其他商品')
          return false
        }
        this.formData.boxGoods.push({
          seriesId: this.id,
          type: 1,
          goodsId: this.tempGoodsDetail.goods.goodsId,
          goodsSkuId: this.tempGoodsDetail.goodsAttr[this.tempGoodsAttrIndex]
            .skuCode,
          roles: '0,1',
          tempRoles: [0, 1],
          name: this.tempGoodsDetail.goods.name,
          subTitle: this.tempGoodsDetail.goods.subName,
          goodsLabel:'',
          boxCount: 1,
          minnum: '',
          boxNum: '',
          regionPrice: '',
          directorPrice: '',
          areaCommission: '',
          recommAreaCommission: '',
          recommDirectorCommission: '',
          directorCommission: '',
          image: this.tempGoodsDetail.goods.image,
          imageList: '',
          tempImageList:
            this.tempGoodsDetail.goods.goodsGalleryList.map(item => item.url) ||
            [],
          intro: this.tempGoodsDetail.goods.intro,
          story: this.tempGoodsDetail.goods.story,
          comment: this.tempGoodsDetail.goods.comment,
          goodsAttr: {
            ...this.tempGoodsDetail.goodsAttr[this.tempGoodsAttrIndex],
            associationId: this.id
          },
          boxPresentGoods: [],
          upshelf: 1,
          isSell: 1
        })
      } else {
        if (
          this.tempGoodsItem.boxPresentGoods.some(
            item =>
              item.goodsSkuId ===
              this.tempGoodsDetail.goodsAttr[this.tempGoodsAttrIndex].skuCode
          )
        ) {
          this.$message.warning('商品已存在，请选择其他商品')
          return false
        }

        this.tempGoodsItem.boxPresentGoods = [
          {
            type: 0,
            boxId: this.tempGoodsItem.boxId ? this.tempGoodsItem.boxId : null,
            goodsId: this.tempGoodsDetail.goods.goodsId,
            goodsSkuId: this.tempGoodsDetail.goodsAttr[this.tempGoodsAttrIndex]
              .skuCode,
            name: this.tempGoodsDetail.goods.name,
            img: this.tempGoodsDetail.goods.image,
            roles: '0,1',
            rule: 1,
            buyNum: 1,
            giveNum: 1,
            buyNum2: 0,
            giveNum2: 0,
            boxCount: 1,
            presentNum: 1,
            deleteFlag: 1,
            isSecondRule: false,
            goodsAttr: {
              ...this.tempGoodsDetail.goodsAttr[this.tempGoodsAttrIndex],
              associationId: this.id
            }
          }
        ].concat(this.tempGoodsItem.boxPresentGoods)
      }
      this.showSelectPop = false
    },
    mixinsFormScrollIntoView() {
      this.$nextTick(() => {
        const isError = document.getElementsByClassName('is-error');
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: 'center',
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: 'smooth'
        });
      });
    },
    save() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          this.$message.error('请完善表单');
          this.mixinsFormScrollIntoView();
          return false
        }
        this.formData.boxGoods.map(item => {
          item.roles = item.tempRoles.join(',')
          item.imageList = item.tempImageList.join(',')
        })
        this.formData.boxSeries.freightTemplateId = Number(
          this.formData.boxSeries.freightTemplateId
        )
        this.saveLoading = true
        // console.log(JSON.stringify(this.formData));
        this.request({
          url: '/bsnl-product/box/goods/doSave',
          method: 'post',
          data: this.formData
        })
          .then(() => {
            this.$message.success('保存成功')
            this.saveLoading = false
            this.$router.push({ name: 'boxTransActivity' })
          })
          .catch(err => {
            console.error(err)
            this.saveLoading = false
          })
      })
    }
  }
}
</script>
<style lang="scss">
.section-header {
  margin-bottom: 32px;
  padding: 12px;
  background: #f8f8f8;
  box-sizing: border-box;
  span {
    color: #333;
    font-size: 14px;
    line-height: 12px;
    padding: 0 12px;
    border-left: 1px solid #409eff;
  }
}
.section-content {
  .line {
    text-align: center;
  }
  .el-input {
    width: 100%;
    max-width: 500px;
    min-width: 150px;
  }
  .el-icon-delete {
    color: red;
    font-size: 16px;
    margin: 0 12px;
    cursor: pointer;
  }
  .goods-item {
    padding: 12px 0;
    // border: 1px solid #efefef;
    border-radius: 6px;
    position: relative;

    .avatar-uploader .el-upload,
    .upload-img-list li,
    .upload-img-list .upload-btn {
      width: 120px;
      height: 120px;
      line-height: 118px;
    }
    .upload-img-list .img-preview .img-preview-mask .mask-btn {
      margin-top: 47px;
      line-height: 36px;
      text-align: center;
    }

    .present-item {
      padding: 6px;
      border: 1px solid #efefef;
      margin-bottom: 12px;
      position: relative;

      .el-icon-error {
        color: red;
        font-size: 18px;
        cursor: pointer;
        top: 12px;
        right: 12px;
        position: absolute;
        z-index: 9;
      }

      & > .el-form-item {
        margin-bottom: 22px;
      }
      .el-input,
      .el-select {
        width: 100%;
        max-width: 160px;
      }
    }
  }
  .add-btn-block {
    margin: 0 0 12px 24px;
  }
  .footer-block {
    text-align: center;
    margin-top: 24px;
  }
}
</style>
